<?php

/**
 * Created by PhpStorm.
 * User: t
 * Date: 2024/6/21
 * Time: 15:31
 */

namespace app\home\controller;


use app\common\model\Config;
use app\common\model\Level;
use app\common\model\LevelCami;
use app\common\model\LevelOrder;
use app\common\model\PayAmount;
use app\common\model\RechargeOrder;
use app\common\model\UserGzh;
use app\common\model\UserLevel;
use app\common\model\UserXcx;
use app\Request;
use app\services\wechat\Miniprogram;
use app\services\wechat\Offiaccount;

class Order
{
    public function buyVip(Request $request)
    {
        $param = $request->param();
        $levelModel = new Level();
        $levelInfo = $levelModel->where(['id' => $param['id']])->find();
        $data = [
            'level_id' => $param['id'],
            'order_sn' => getOrderNo('l_'),
            'type' => 1,
            'status' => 1,
            'uid' => $request->userInfo['id'],
            'price' => $levelInfo['price'],
            'create_time' => time(),
            'pay_type' => $param['pay_type'],
            'effective_time' => $levelInfo['effective_time'],
        ];
        $pay_type = Config::getConfigValue('pay_type');
        $data['merchant_type']  = $pay_type;
        $levelOrder = new LevelOrder();
        $levelOrder->insert($data);
        if ($param['pay_type'] == 1){
            $miniprogram = new Miniprogram();
            $userXcxModel  = new UserXcx();
            $userXcxInfo = $userXcxModel->where(['id' => $request->userInfo['user_xcx_id']])->find();
            if ($pay_type == 1){
                $WechatInfo =  $miniprogram-> wechatpay($data,$userXcxInfo['openid'],'购买vip','levelXcxOrder');
            }else{
                $WechatInfo=  $miniprogram-> mWechatpay($data,$userXcxInfo['openid'],'购买vip','levelXcxOrder');
            }
            if ($WechatInfo['code'] == 1) {
                return success('成功', $WechatInfo['data']);
            } else {
                return error($WechatInfo['msg']);
            }
        }else{
           $offiaccunt =  new Offiaccount();
           $userGzhModel  = new UserGzh();
           $userGzhInfo = $userGzhModel->where(['id' => $request->userInfo['user_gzh_id']])->find();
            if ($pay_type == 1){
                $WechatInfo =  $offiaccunt-> wechatpay($data,$userGzhInfo['openid'],'购买vip','levelGzhOrder');
            }else{
                $WechatInfo=  $offiaccunt-> mWechatpay($data,$userGzhInfo['openid'],'购买vip','levelGzhOrder');
            }
            if ($WechatInfo['code'] == 1) {
                return success('成功', $WechatInfo['data']);
            } else {
                return error($WechatInfo['msg']);
            }
        }
    }
    public function exchangeVip(Request $request){
        $param  = $request->param();
        $levelCami  = new LevelCami();
        $camiInfo = $levelCami->where(['round_str' => $param['round_str']])->find();
        try{
            $levelCami->startTrans();
            if ($camiInfo){
                if ($camiInfo['status']  == 1){
                    $userLevelModel  = new UserLevel();
                    $levelModel = new Level();
                    $levelInfo  = $levelModel->where(['id' => $camiInfo['level_id']])->find(); // 会员等级时间
                    $userLevelInfo  = $userLevelModel->where(['uid'=>$request->userInfo['id'],'level_id'=>$camiInfo['level_id']])->find();// 用户会员状态
                    if ($userLevelInfo){// 是否存在当前会员
                        $mostLevel  = $userLevelModel->where('level','>',$userLevelInfo['level'])->where(['uid'=>$request->userInfo['id'],'status' => 1])->find();
                        if($mostLevel){
                            return error('目前会员等级高于兑换等级,请过期后再使用');
                        }
                        if ($userLevelInfo['status'] == 1){
                            $endTime = strtotime($userLevelInfo['end_time'] )+ 86400 * $levelInfo['effective_time'];
                            $userLevelModel->where(['uid'=>$request->userInfo['id'],'level_id'=>$camiInfo['level_id']])->update(['end_time' =>$endTime ]);
                        }else{
                            $startTime = time();
                            $endTime =$startTime + 86400 * $levelInfo['effective_time'];
                            $userLevelModel
                                ->where(['uid'=>$request->userInfo['id'],'level_id'=>$camiInfo['level_id']])
                                ->update(['end_time' =>$endTime, 'start_time' =>  $startTime]);
                            $userMode = new \app\common\model\User();
                            $userMode->where(['id' => $request->userInfo['id']])->update(['level_id' =>$levelInfo['id'],'level_name' => $levelInfo['name']]);

                        }
                    }else{
                        $startTime = time();
                        $endTime =$startTime + 86400 * $levelInfo['effective_time'];
                        $data = [
                            'start_time' => $startTime,
                            'end_time'=> $endTime,
                            'uid' => $request->userInfo['id'],
                            'level_id' =>$levelInfo['id'],
                            'level' =>$levelInfo['level'],
                        ];
                        $userLevelModel->insert($data);
                        $userMode = new \app\common\model\User();

                        $userMode->where(['id' => $request->userInfo['id']])->update(['level_id' =>$levelInfo['id'],'level_name' => $levelInfo['name']]);
                    }
                    $levelCami->where(['round_str' => $param['round_str']])->update(['status' => 2,'uid' => $request->userInfo['id'],'use_time' => time()]);
                    $lowLevel  = $userLevelModel->where('level','<',$levelInfo['level'])->where(['uid'=>$request->userInfo['id'],'status' => 1])->select()->toArray();
                    if ($lowLevel ){
                        foreach ($lowLevel  as $value ){
                            $effectiveTime = abs($value['time'] - time()) / 86400;
                            $lowLevelTime  = $endTime + $effectiveTime;
                            $userLevelModel->where(['id' => $value['id']])->update(['end_time' => $lowLevelTime])->update();
                        }
                    }
                    $levelOrder = new LevelOrder();
                    $orderData =[
                        'order_sn'=> getOrderNo('l_'),
                        'uid' => $request->userInfo['id'],
                        'level_id' => $camiInfo['level_id'],
                        'create_time' => time(),
                        'type' => 2,
                        'status'=> 2,
                        'price' => 0,
                        'cami_id' =>$camiInfo['id'],
                        'pay_time'=> time(),
                        'effective_time' => $levelInfo['effective_time'],
                        'pay_type' => 0,
                        'merchant_type' => 0,
                    ];
                    $levelOrder->insert($orderData);
                    $levelCami->commit();
                }else{
                    return error('卡密已使用');
                }
            }else{
                return error('卡密有误');
            }
        }catch (\Exception $exception){
            $levelCami->rollback();
            return error($exception->getMessage().$exception->getLine());
        }
        return success('兑换成功');
    }
    public function rechargeOrder(Request $request){
        $param  = $request->param();
        $payAmountModel  = new PayAmount();
        $payAmount = $payAmountModel->where(['id' => $param['pay_amount_id']])->find();
        $data = [
            'order_sn' => getOrderNo('r_'),
            'uid' => $request->userInfo['id'],
            'price' => $payAmount['price'],
            'amount' => $payAmount['amount'],
            'give_amount' => $payAmount['give_amount'],
            'create_time'=> time(),
            'pay_amount_id' => $param['pay_amount_id'],
            'pay_type' => $param['pay_type'],
        ];
        $pay_type = Config::getConfigValue('pay_type');
        $data['merchant_type']  = $pay_type;
        $rechargeOrderModel  =  new  RechargeOrder();
        $rechargeOrderModel->insert($data);
        if ($param['pay_type'] == 1){
            $miniprogram = new Miniprogram();
            $userXcxModel  = new UserXcx();
            $userXcxInfo = $userXcxModel->where(['id' => $request->userInfo['user_xcx_id']])->find();
            if ($pay_type == 1){
                $WechatInfo =  $miniprogram-> wechatpay($data,$userXcxInfo['openid'],'购买vip','rechargeXcxOrder');
            }else{
                $WechatInfo=  $miniprogram-> mWechatpay($data,$userXcxInfo['openid'],'购买vip','rechargeXcxOrder');
            }
            if ($WechatInfo['code'] == 1) {
                return success('成功', $WechatInfo['data']);
            } else {
                return error($WechatInfo['msg']);
            }
        }else{
            $offiaccunt =  new Offiaccount();
            $userGzhModel  = new UserGzh();
            $userGzhInfo = $userGzhModel->where(['id' => $request->userInfo['user_gzh_id']])->find();
            if ($pay_type == 1){
                $WechatInfo =  $offiaccunt-> wechatpay($data,$userGzhInfo['openid'],'购买vip','rechargeGzhOrder');
            }else{
                $WechatInfo=  $offiaccunt-> mWechatpay($data,$userGzhInfo['openid'],'购买vip','rechargeGzhOrder');
            }
            if ($WechatInfo['code'] == 1) {
                return success('成功', $WechatInfo['data']);
            } else {
                return error($WechatInfo['msg']);
            }
        }

    }
    public function rechargeOrderList(Request $request){
        $param = $request->param();
        $limit = 10;
        $start = 0;
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }
        $where[] = ['uid','=',$request->userInfo['id']];

        if (isset($param['status']) && !empty($param['status'])) {
            $where[] = ['status','=',$param['status']];
        }
        if (isset($param['order_sn']) && !empty($param['order_sn'])) {
            $where[] = ['order_sn','like','%'.$param['order_sn'].'%'];
        }

        $rechargeOrderModel = new \app\common\model\RechargeOrder();
        $list = $rechargeOrderModel ->alias('re')
            ->where($where)
            ->limit($start, $limit)
            ->select()->toArray();
        $count = $rechargeOrderModel
            ->where($where)->count();
        return success('充值记录', ['list' => $list, 'count' => $count]);
    }

    public function userLevelOrderList(Request $request){
        $param = $request->param();
        $limit = 10;
        $start = 0;
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }
        $where = [];
        $where[] = ['uid','=',$request->userInfo['id']];
        if (isset($param['status']) && !empty($param['status'])) {
            $where[] = ['lo.status','=',$param['status']];
        }
        if (isset($param['type']) && !empty($param['type'])) {
            $where[] = ['lo.type','=',$param['type']];
        }
        if (isset($param['start_time']) && !empty($param['start_time'])) {
            $where[] = ['lo.create_time', '>=', strtotime($param['start_time'])];
        }
        if (isset($param['end_time']) && !empty($param['end_time'])) {
            $where[] = ['lo.create_time', '>=', strtotime($param['end_time'])];
        }
        $levelOrderModel = new \app\common\model\LevelOrder();
        $list = $levelOrderModel ->alias('lo')
            ->leftJoin('level l','l.id = lo.level_id')
            ->where($where)
            ->field('lo.*,l.name,l.desc,l.effective_time,l.name')
            ->limit($start, $limit)
            ->select()->toArray();
        $count = $levelOrderModel ->alias('lo')
            ->leftJoin('user u','lo.uid = u.id')
            ->leftJoin('level l','l.id = lo.level_id')
            ->where($where)->count();
        return success('会员购买记录', ['list' => $list, 'count' => $count]);
    }
    /**
     * * @copyright: ©2024 永州微聚 商网络科技有限公司
     * @link: https://www.weijuYunke.com
     */
}
